import axios from 'axios'
// 图片压缩处理工具 IOS兼容有问题
// import lrz from 'lrz'

export default function uploadFile(vueInstance, files, success, failure, showLoading = true) {
  if (showLoading) {
    vueInstance.$vux.loading.show({
      text: '上传中...'
    })
  }
  axios.defaults.timeout = 30000

  let config = {
    processData: false, // *重要,确认为false
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
  let param = new FormData()
  for (let i = 0; i < files.length; i++) {
    if (files[i].filename) {
      param.append('file', files[i])
    } else {
      param.append('file', files[i], 'image.png')
    }
  }
  axios.post('http://120.79.17.68:9001/apiAttachment/uploadAttachment', param, config).then(res => {
  // axios.post('http://192.168.0.135:9001/apiAttachment/uploadAttachment', param, config).then(res => {
    if (showLoading) {
      vueInstance.$vux.loading.hide()
    }
    if (res.data.code === 0) {
      if (success) {
        return success(res.data.data)
      }
    } else {
      if (failure) {
        failure(res.data)
      } else {
        vueInstance.$vux.toast.text(res.data.message, 'middle')
        console.error('api error: ' + res.data.message)
      }
    }
  }).catch(e => {
    if (showLoading) {
      vueInstance.$vux.loading.hide()
    }
    vueInstance.$vux.toast.text('网络错误', 'middle')
    if (e) {
      console.error('upload file error, HTTP CODE: ' + e.message)
    }
  })
}
